import { IChannel, IGuess } from "@/models/home";
import { RootState } from "@/models/index";
import { HomeParamList } from "@/navigator/HomeTabs";
import { RouteProp } from "@react-navigation/native";
import React from "react";
import { FlatList, ListRenderItemInfo, NativeScrollEvent, NativeSyntheticEvent, StyleSheet, Text, View } from "react-native";
import { connect, ConnectedProps } from 'react-redux';
import { RootStackNavigation } from "../../navigator";
import Carousel, { sideHeight } from "./Carousel";
import ChannelItem from "./ChannelItem";
import Guess from "./Guess";

const mapStateToProps = (state: RootState, {route}: {route: RouteProp<HomeParamList, string>}) => {
  const {namespace} = route.params;
  const modelState = state[namespace];
  return {
    namespace,
    carousels: modelState.carousels,
    channels: modelState.channels,
    hasMore: modelState.pagination.hasMore,
    loading: state.loading.effects[namespace + '/fetchChannels'],
    gradientVisible: modelState.gradientVisible,
  }
};

const connector = connect(mapStateToProps);

type ModelState = ConnectedProps<typeof connector>;

interface IProp extends ModelState {
  navigation: RootStackNavigation;
}

interface IState {
  refreshing: boolean;
}


class Home extends React.Component<IProp, IState> {

  state = {
    refreshing: false,
  }

  componentDidMount() {
    const { dispatch, namespace} = this.props;
    dispatch({
      type: namespace + '/fetchCarousels',
    });
    dispatch({
      type: namespace + '/fetchChannels',
    })
  }

  goAblum = (data: IChannel | IGuess) => {
    const {navigation} = this.props;
    navigation.navigate("Album", {item: data});

  };

  keyExtractor = (item: IChannel) => {
    return item.id;
  }

  onRefresh = () => {
    //1.修改刷新状态为true
    this.setState({
      refreshing: true,
    })
    //2.获取数据
    const {dispatch, namespace} = this.props;
    dispatch({
      type: namespace + '/fetchChannels',
      callback: () => {
        this.setState({
          refreshing: false,
        })
      }
    })
  }

  //加载更多
  onEndReached = () => {
    const {dispatch, loading, hasMore, namespace} = this.props;
    if (loading || !hasMore) {
      return;
    }
    dispatch({
      type: namespace + '/fetchChannels',
      payload: {
        loadMore: true,
      }
    })
  }

  renderItem = ({ item }: ListRenderItemInfo<IChannel>) => {
    return (
      <ChannelItem data={item} onPress={this.goAblum} />
    );
  }

  onScroll = ({nativeEvent}: NativeSyntheticEvent<NativeScrollEvent>) => {
    const offsetY = nativeEvent.contentOffset.y;
    let newGradientVisible = offsetY < sideHeight;
    const {dispatch, gradientVisible, namespace} = this.props;
    if (newGradientVisible !== gradientVisible) {
      dispatch({
        type: namespace + '/setState',
        payload: {
          gradientVisible: newGradientVisible
        }
      })
    }
    
  }

  get header() {
    const {namespace} = this.props;
    
    return (
      <View>
        <Carousel  />
        <View style={styles.background}>
          <Guess namespace={namespace} goAlbum={this.goAblum}/>
        </View>
      </View>
    );
  }

  get footer() {
    const {hasMore, loading, channels} = this.props;
    if (!hasMore) {
      return (
        <View style={styles.end}>
          <Text>--我是有底线的--</Text>
        </View>
      );
    }
    if (loading && hasMore && channels.length > 0) {
      return (
        <View style={styles.loading}>
          <Text>loading...</Text>
        </View>
      );
    }
  }

  get empty() {
    const {loading} = this.props;
    if (loading) return;
    return (
      <View style={styles.empty}>
        <Text>暂无数据</Text>
      </View>
    );
  }

  render() {
    const { channels } = this.props;
    const {refreshing} = this.state;
    return (

      <FlatList
        ListHeaderComponent={this.header}
        data={channels}
        renderItem={this.renderItem}
        keyExtractor={this.keyExtractor}
        onRefresh={this.onRefresh}
        refreshing={refreshing}
        onEndReached={this.onEndReached}
        onEndReachedThreshold={0.2}
        ListFooterComponent={this.footer}
        ListEmptyComponent={this.empty}
        onScroll={this.onScroll}
      />
    )
  }
}

const styles = StyleSheet.create({
  end: {
    alignItems: 'center',
    paddingVertical: 10,

  },
  loading: {
    alignItems: 'center',
    paddingVertical: 10,
  },
  empty: {
    alignItems: 'center',
    paddingVertical: 100,
  },
  background: {
    backgroundColor: '#fff'
  }
});

export default connector(Home);